package com.cofi.vueelementadminserver.config.security;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xyh
 * @date 2024-12-30
 * @description 认证成功处理
 */
public class MyLoginSuccessHandler extends UsernamePasswordAuthenticationFilter implements AuthenticationSuccessHandler  {
    private String key= "1234567890_0123456789_abcdefghigklmn";

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取用户身份信息
        SecurityUserDetail userDetails = (SecurityUserDetail) authentication.getPrincipal();

        Enumeration<String> headerNames = request.getHeaderNames();

        Map<String,Object> result = new HashMap<>();
        result.put("status", "200");
        result.put("code",0);
        result.put("message","success");

        Map<String,Object> playloadMap = new HashMap<>();
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userDetails.getId());
        claims.put("username", userDetails.getLogName());
        String token = JWTUtil.createToken(claims, key.getBytes());
//        playloadMap.put("token","Bearer " + token);
        playloadMap.put("token","Bearer " + token);
        result.put("data",playloadMap);


        String resultJson = JSON.toJSONString(result);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(resultJson);
    }
}
